package com.atguigu.gulimall.ware.lisitener;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.to.mq.TaskDetailEntityTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class ReleaseStockLinistener {

    @Autowired
    WareOrderTaskDetailService taskDetailService;
    @Autowired
    WareOrderTaskService taskService;
    @Autowired
    OrderFeignService orderFeignService;
    @Autowired
    WareSkuDao wareSkuDao;

    @RabbitHandler
    public void releaseHandle(StockLockedTo stockLockedTo, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存消息");
        try {

            this.unlocked(stockLockedTo);
//                    告诉mq 手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            //                拒接收到消息，重新放到队列里
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
    @RabbitHandler
    public void releaseOrderHandle(String orderSn,Message message,Channel channel) throws IOException {
        System.out.println("收到订单解锁消息，开始尝试解锁库存");
        try {
            this.unlocked(orderSn);
//                    告诉mq 手动ack
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

    public void unlocked(StockLockedTo stockLockedTo){
        Long taskId = stockLockedTo.getTaskId();
        TaskDetailEntityTo detailEntityTo = stockLockedTo.getDetailEntityTo();
        Long detailEntityToId = detailEntityTo.getId();
        WareOrderTaskDetailEntity taskDetailEntity = taskDetailService.getById(detailEntityToId);
        if (taskDetailEntity!=null){
            //解锁
//            判断订单是否异常 订单异常才解锁，订单不异常 不解锁
//               （订单存在并且订单状态为4） 或者 订单不存在 已取消时 进行解锁
            //根据orderSn调用远程 查询订单状态
            WareOrderTaskEntity taskEntity = taskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();

            R r=orderFeignService.getStatusByOrderSn(orderSn);

            if(r.getCode()==0){
                OrderVo data = r.getData("data", new TypeReference<OrderVo>() {
                });
                if (data==null || data.getStatus()==4){
//                    解锁订单
                    Long skuId = taskDetailEntity.getSkuId();
                    Integer skuNum = taskDetailEntity.getSkuNum();
                    Long wareId = taskDetailEntity.getWareId();
                    if (taskDetailEntity.getLockStatus()==1){
//                  解锁
                        wareSkuDao.unlocked(skuId,skuNum,wareId,detailEntityToId);
                        //更新taskdetail的状态为2
                        taskDetailEntity.setLockStatus(2);
                        taskDetailService.updateById(taskDetailEntity);
                    }
                }
            }else {
                throw new RuntimeException("远程服务失败");
            }
        }
    }

@Transactional
    public void unlocked(String orderSn){
        WareOrderTaskEntity taskEntity = taskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));
        Long taskEntityId = taskEntity.getId();
    List<WareOrderTaskDetailEntity> taskDetailEntities = taskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", taskEntityId).eq("lock_status", 1));
    for (WareOrderTaskDetailEntity taskDetailEntity : taskDetailEntities) {
        wareSkuDao.unlocked(taskDetailEntity.getSkuId(),taskDetailEntity.getSkuNum(),taskDetailEntity.getWareId(),taskDetailEntity.getId());
        taskDetailEntity.setLockStatus(2);
        taskDetailService.updateById(taskDetailEntity);
    }

}
}
